package redis;

import java.math.BigDecimal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import redis.clients.jedis.Jedis;

/**
 * Redis检测
 * <p>
 * 输入参数：
 * <ul>
 * <li>host: 主机地址(必须)，如 192.168.1.105</li>
 * <li>port: 端口(必须)，如 8888</li>
 * </ul>
 * 输出指标：
 * <ul>
 * <li>status: 状态，如 0，1</li>
 * </ul>
 * </p>
 * 
 * @date 2013-9-25 下午6:17:22
 */
public class RedisInfo {
	private final static Log log = LogFactory.getLog(RedisInfo.class);

	public void execute(String host, Integer port) {	
		Jedis client = null;
		try {
			client = new Jedis(host, port);
			System.out.println(client.info());
			//Map<String, Object> data = getIndicators(client.info());
			//System.out.println(data.toString());
		
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (client != null) {
				try {
					client.quit();
				} catch (Exception e) {
				}
				client = null;
			}
		}
		
	}

/*	private Map<String, Object> getIndicators(String redisInfo) {
		String[] keyValues = redisInfo.split("\r\n");
//System.out.println(redisInfo);
		Map<String, String> redisMap = new HashMap<String, String>();
		for (String keyValue : keyValues) {
			String[] singleKeyValue = keyValue.split(":");
			redisMap.put(singleKeyValue[0], singleKeyValue[1]);
		}

		// 指标数据
		Map<String, Object> data = new HashMap<String, Object>();

		double userdMemory = Double.parseDouble(redisMap.get("used_memory").trim());
		data.put("usedMem", formatToFloat(userdMemory / 1048576));

		double hit = Double.parseDouble(redisMap.get("keyspace_hits").trim());
		double miss = Double.parseDouble(redisMap.get("keyspace_misses").trim());
		double connectedClients = Double.parseDouble(redisMap.get("connected_clients").trim());
		
		if (hit + miss == 0) {
			data.put("keySpaceRatio", 0.00);
		} else {
			data.put("keySpaceRatio", formatToFloat(hit * 100 / (hit + miss)));
		}
		
		data.put("hits", hit);
		data.put("misses", miss);
		data.put("connectedClients", connectedClients);
		
		return data;
	}*/

	/**
	 * 将双精度型数字转换为浮点型的数值，并以四舍五入的方式保留两位小数
	 * 
	 * @param oriNum
	 *            原始的双精度型数字
	 * @return
	 */
	private float formatToFloat(double oriNum) {
		BigDecimal bigDecimal = new BigDecimal(oriNum);
		float result = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		return result;
	}

	public static void main(String[] args) {
		new RedisInfo().execute("10.121.49.131", 6379);
		
		//new RedisInfo().execute("10.10.136.40", 6379);
	}


}
